﻿using DataGridViewAutoFilter;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Xml;
using System.Diagnostics;
using System.IO;

namespace RemoteUser
{
    public partial class PLCListForm : Form
    {
        #region 内部变量
        //修改本界面上的关键信息
        private delegate void ModifyImportantMsg(string importantMsg);
        //修改本届面上的PLC列表
        private delegate void ModifyPLCList(XmlDocument xDocument);
        //调用远程桌面
        private delegate void CallTheRemoteDesktop();
        //关闭本窗口及本窗口之后建立的所有窗口（包括联系信息，全部参数）
        private delegate void CancelTheFroms();
      
        public bool PLCAllParmsFormIsExisted = false;
        public bool PLCConnInfoFormIsExisted = false;
        public bool PLCAbnormalInfoFormIsExisted = false;
        public bool modifyPersonalInfoFormIsExisted = false;
        public bool theConnectionIsWrong = false;
        
        //保存全部参数子窗体对象的静态变量（此处应该可以用private）
        private static PLCAllParmsForm pPLCAllParmsForm;
        private static PLCConnInfoForm pPLCConnInfoForm;
        private static PLCAbnormalInfoForm pPLCAbnormalInfoForm;
        private static ModifyPersonalInfoForm pModifyPersonalInfoForm; 
        //阻塞recv线程是否要继续
        private bool threadNeedGoing = true;         
        //保存socket与stream 原则上一个就够
        private Socket mySocket;
        private NetworkStream myStream;
        //登录的用户ID
        private string myID;        
        //表中选中的PLCID PLCName
        private string currentPLCID{ get; set; }
        private string currentPLCName { get; set; }        
        //连接远程桌面的IP:PORT
        private string remoteIp;
        private string remotePort;
        private string computername;
        private string computerpasswd;
        //是否要继续检测远程桌面进程，抓取句柄后，线程结束
        private bool CheckThreadIsGoing;
        private Thread listenThread = null;

        private BindingCollection<PLC> PLCsData;
        private BindingCollection<RemoteAndLocalUserInfo> localUserInfo;
        private BindingCollection<RemoteAndLocalUserInfo> remoteUserInfo;
        private BindingCollection<ParmNode> produceCraftsAllParms;
        private BindingCollection<ParmNode> deviceStatusAllParms;
        private BindingCollection<ParmNode> produceCraftsKeyParms;
        private BindingCollection<ParmNode> deviceStatusKeyParms;
        private BindingCollection<AbnormalInfo> abnormalInfo;
        private string produceCraftsknowledgeInfo;
        private string deviceStatusknowledgeInfo;
        private string PLCConnInfoOfCompany;
        private QQInfo qqInfo;
        private string reason;
        private DataSet PLCListDataSet;
        StatusStrip statusStrip1 = new StatusStrip();
        ToolStripStatusLabel filterStatusLabel = new ToolStripStatusLabel();
        ToolStripStatusLabel showAllLabel = new ToolStripStatusLabel("Show &All");
        private string[] oldPersonalInfo;
        private string[] newPersonalInfo;
        #endregion
        public PLCListForm()
        {
            InitializeComponent();           
        }

        public PLCListForm(Socket myClientSocket,NetworkStream netstream,string ID)
        {
            InitializeComponent();
            mySocket = myClientSocket;
            myStream = netstream;
            myID = ID;
            this.userNameLabel.Text = myID;
            //重载关闭和列表排序
            this.Closing += new CancelEventHandler(CancleButtonClick);

            showAllLabel.Visible = false;
            showAllLabel.IsLink = true;
            showAllLabel.LinkBehavior = LinkBehavior.HoverUnderline;
            showAllLabel.Click += new EventHandler(showAllLabel_Click);

            statusStrip1.Cursor = Cursors.Default;
            statusStrip1.Items.AddRange(new ToolStripItem[] { 
                filterStatusLabel, showAllLabel });

            this.Controls.AddRange(new Control[] {
                PLCListDataGridView, statusStrip1 });
        }
        
        private void PlCListViewForm_Load(object sender, EventArgs e)
        {
            //先主动发送一个PLC列表请求
            SendAndRecv.SendPLCListRequest(myStream, myID);
            //开启线程监听所有报文
            listenThread = new Thread(RecvMsg);
            listenThread.IsBackground = true;
            listenThread.Start();
        }

        private void RecvMsg()
        {
            try
            {
                #region 阻塞的recv接收所有报文
                while (threadNeedGoing)
                {   
                    //收到一个完整的报文，并检测其是否是 PLS 和 ver = 1
                    XmlDocument xDocument = SendAndRecv.pullXmlFromServer(mySocket);
                    if (xDocument == null)
                    {
                        threadNeedGoing = false;                        
                        break;
                    };
                    int ver = TranslateXml.GetPLSVer(xDocument);
                    if (ver != 1)
                        continue;
                    int type = -1;
                    type = TranslateXml.GetPLSType(xDocument);
                    if (type == -1)
                        continue;
                    //这里根据不同的报文进行不同的处理。
                    switch (type)
                    {
                        #region PLC列表的反馈报文
                        case 34:
                            {
                                int returnCode = TranslateXml.GetPLSRetrunCode(xDocument);
                                switch (returnCode)
                                {
                                    case 0:
                                        {
                                            //读取所有的PLC信息.
                                            PLCsData = TranslateXml.GetPLSPLCList(xDocument);
                                            if (PLCsData == null)
                                                break;
                                            StringBuilder tempPLCList = new StringBuilder();
                                            foreach (var PLCNodeInList in PLCsData)
                                            {
                                                if (PLCNodeInList.PLCAbnormal != "0")
                                                {
                                                    tempPLCList.AppendFormat("PLC名称{0} :异常信息--{1}\n", PLCNodeInList.PLCID, PLCNodeInList.PLCMsg);              
                                                }
                                            }
                                            if (this.InvokeRequired)
                                                this.Invoke(new ModifyImportantMsg(ModifyImportantMsgRichTextBox), tempPLCList.ToString());
                                            if (this.InvokeRequired)
                                                this.Invoke(new ModifyPLCList(ModifyPLCListView),xDocument);


                                        }
                                        break;
                                    case 221:
                                    case 222:
                                    case 223:
                                        {
                                            string msg = TranslateXml.GetPLSMsg(xDocument);
                                            MessageBox.Show(msg, "错误提示");
                                            break;
                                        }
                                    default:
                                        break;
                                }
                            }
                            break;
                        #endregion
                        #region PLC联系信息报文
                        case 36:
                            {
                                int returnCode = TranslateXml.GetPLSRetrunCode(xDocument);
                                switch (returnCode)
                                {
                                    case 0:
                                        {   //若窗口已关闭，则忽略次报文。
                                            if (!PLCConnInfoFormIsExisted)
                                                continue;
                                            qqInfo = TranslateXml.GetQQInfo(xDocument);
                                            Trace.WriteLine(qqInfo.yourQQ+"  "+qqInfo.yourQQpwd);
                                            PLCConnInfoOfCompany = TranslateXml.GetPLCConnInfo(xDocument);
                                            
                                            if (this.InvokeRequired)
                                                this.Invoke(new PLCConnInfoForm.ModifyPLCConnInfo(
                                                    pPLCConnInfoForm.ModifyPLCConnInfoRichTextBox), PLCConnInfoOfCompany);
                                            
                                            localUserInfo = TranslateXml.GetPLCConnInfoUser(xDocument, 0);
                                            remoteUserInfo = TranslateXml.GetPLCConnInfoUser(xDocument, 1);

                                            object userInfo1 = (object)localUserInfo;
                                            object userInfo2 = (object)remoteUserInfo;
                                            
                                            if(this.InvokeRequired)
                                                this.Invoke(new PLCConnInfoForm.ModifyUserInfo(
                                                    pPLCConnInfoForm.ModifyTheUserInfoData), userInfo1,userInfo2);             
                                        }
                                        break;
                                    default:
                                        {
                                            MessageBox.Show("全部参数有误反馈");
                                        }
                                        break;
                                }     
                            }
                            break;
                        #endregion
                        #region PLC关键参数
                        case 38:
                            {
                                Debug.WriteLine(" 你收到了关键参数");
                                int returnCode = TranslateXml.GetPLSRetrunCode(xDocument);
                                switch (returnCode)
                                {
                                    case 0:
                                        {   //若窗口已关闭，则忽略次报文。
                                            if (!PLCConnInfoFormIsExisted)
                                                continue;
                                            //处理全部参数                                   
                                            produceCraftsKeyParms = TranslateXml.GetParmsList(xDocument, 2);

                                            var parms1 = produceCraftsKeyParms;
                                            if (produceCraftsKeyParms == null)
                                                break;
                                            deviceStatusKeyParms = TranslateXml.GetParmsList(xDocument, 3);

                                            var parms2 = deviceStatusKeyParms;
                                            if (deviceStatusKeyParms == null)
                                                break;

                                            produceCraftsknowledgeInfo = TranslateXml.GetParmsknowledgeInfo(xDocument,2);
                                            deviceStatusknowledgeInfo =TranslateXml.GetParmsknowledgeInfo(xDocument,3);
                                            
                                            if (this.InvokeRequired)
                                                this.Invoke(new PLCConnInfoForm.ModifyKeyParms(pPLCConnInfoForm.ModifyKeyParmsData),
                                                    (object)parms1, 
                                                    (object)parms2,
                                                    produceCraftsknowledgeInfo,
                                                    deviceStatusknowledgeInfo);
                                        }
                                        break;
                                    default:
                                        {
                                            MessageBox.Show("全部参数有误反馈");
                                        }
                                        break;
                                }
                                break;
                            }
                        #endregion
                        #region PLC全部参数
                        case 40:
                            {
                                int returnCode = TranslateXml.GetPLSRetrunCode(xDocument);    
                                switch (returnCode)
                                {
                                    case 0:
                                        {   //若窗口已关闭，则忽略次报文。
                                            if (!PLCAllParmsFormIsExisted)
                                                continue;
                                            //处理全部参数                                   
                                            produceCraftsAllParms = TranslateXml.GetParmsList(xDocument, 0);

                                            var parms1 = produceCraftsAllParms;
                                            if (produceCraftsAllParms == null)
                                                break;      
                                            deviceStatusAllParms = TranslateXml.GetParmsList(xDocument, 1);
                                            
                                            var parms2 = deviceStatusAllParms;
                                            if (deviceStatusAllParms == null)
                                                break;
                                            if (this.InvokeRequired)
                                                this.Invoke(new PLCAllParmsForm.ModifyPLCParmsList(
                                                    pPLCAllParmsForm.ModifyMyParmsData),
                                                    (object)parms1,(object)parms2);                                       
                                        }
                                        break;
                                    default:
                                        {
                                            MessageBox.Show("全部参数有误反馈");  
                                        }
                                        break;
                                }     
                            }
                            break;
                        #endregion
                        #region PLC详细异常
                        case 42:
                            {
                                if (!PLCAbnormalInfoFormIsExisted)
                                    continue;
                                abnormalInfo = TranslateXml.GetAbnormalInfo(xDocument);
                                object parm = (object)abnormalInfo;
                                if (this.InvokeRequired)
                                    this.Invoke(new PLCAbnormalInfoForm.ModifyAbnormalInfo(
                                        pPLCAbnormalInfoForm.ModifyAbnormalInfoData),parm);                                            
                            }
                            break;
                        #endregion
                        #region 旧信息
                        case 44: 
                            {
                                int returnCode = TranslateXml.GetPLSRetrunCode(xDocument);
                                switch (returnCode)
                                {
                                    case 0:
                                        {   //若窗口已关闭，则忽略次报文。
                                            if (!modifyPersonalInfoFormIsExisted)
                                                continue;
                                            //处理全部参数  
                                            oldPersonalInfo = new string[3];
                                            oldPersonalInfo = TranslateXml.GetOldPersonalInfo(xDocument);

                                            if (this.InvokeRequired)
                                                this.Invoke(new ModifyPersonalInfoForm.ModifyOldInfo(
                                                    pModifyPersonalInfoForm.ModifyInfoTextBoxes),
                                                    oldPersonalInfo[0],oldPersonalInfo[1],oldPersonalInfo[2]);
                                        }
                                        break;
                                    default:
                                        {
                                            MessageBox.Show("旧信息有误");
                                        }
                                        break;
                                } 
                            } 
                            break;
                        #endregion
                        #region 修改反馈
                        case 46: 
                            {
                                int returnCode = TranslateXml.GetPLSRetrunCode(xDocument);
                                switch (returnCode)
                                {
                                    case 0:
                                        {   //若窗口已关闭，则忽略次报文。
                                            if (!modifyPersonalInfoFormIsExisted)
                                                continue;
                                            //处理全部参数  
                                            newPersonalInfo = new string[5];
                                            newPersonalInfo = TranslateXml.GetNewPersonalInfo(xDocument);

                                            if (this.InvokeRequired)
                                                this.Invoke(new ModifyPersonalInfoForm.ModifyNewInfo(
                                                    pModifyPersonalInfoForm.ModifyInfoTextBoxes),
                                                    newPersonalInfo[0],newPersonalInfo[1],newPersonalInfo[2],newPersonalInfo[3],newPersonalInfo[4]);
                                        }
                                        break;
                                    default:
                                        {
                                            MessageBox.Show("密码错误，修改信息不成功");
                                        }
                                        break;
                                } 
                            } 
                            break;
                        #endregion
                        #region 远程桌面信息
                        case 50:
                            { 
                                int returnCode = TranslateXml.GetPLSRetrunCode(xDocument);
                                switch (returnCode) 
                                {
                                    case 0:
                                        {
                                            this.remoteIp = TranslateXml.GetRemoteIp(xDocument);
                                            if (remoteIp == null)
                                                break;
                                            this.remotePort = TranslateXml.GetRemotePort(xDocument);
                                            if (remotePort == null)
                                                break;
                                            this.computername = TranslateXml.GetRemoteUserName(xDocument);
                                            if (computername == null)
                                                break;
                                            this.computerpasswd = TranslateXml.GetRemoteUserPwd(xDocument);
                                            //if (computerpasswd == null)
                                            //    break;//此处密码是可以空的
                                            if (this.InvokeRequired)
                                                this.Invoke(new CallTheRemoteDesktop(StartRemoteDesktop));
                                        }
                                        break;
                                    default:
                                        MessageBox.Show("远程消息有误");  
                                        break;
                                }
                            }
                            break;
                        #endregion
                        #region 退出报文反馈
                        case 54:
                            {
                                int returnCode = TranslateXml.GetPLSRetrunCode(xDocument);
                                switch (returnCode)
                                {
                                    case 0:
                                        {
                                            Debug.WriteLine("将退出登录");
                                            threadNeedGoing = false;
                                            continue;
                                        }
                                    default:
                                        {
                                            MessageBox.Show("反馈有误，但还是退出");
                                            threadNeedGoing = false;
                                            continue;
                                        }        
                                }
                            }
                        #endregion
                        #region 强制退出报文处理
                        case 55:
                            {
                                reason = TranslateXml.GetPLSMsg(xDocument);
                                SendAndRecv.SendForcedLogoutRespond(myStream, myID);
                                MessageBox.Show(reason,
                                   "提示",
                                   MessageBoxButtons.OK,
                                   MessageBoxIcon.Information);
                                this.CancelTheFormsRightNow();
                            }
                            //强制退出，暂时没办法
                            break;
                        default:
                            break;
                        #endregion
                    }
                }
                #endregion
                //上个括号结束了while
                if (this.InvokeRequired)
                    this.Invoke(new CancelTheFroms(CancelTheFormsRightNow));
            }
            catch (ThreadAbortException e)
            {
                Debug.WriteLine(e.Message);
                Thread.ResetAbort();
            }
        }
        /// <summary>
        /// 本程序打开 远程桌面 并开启线程抓远程桌面窗口。
        /// </summary>
        private void StartRemoteDesktop()
        { 
            //启动远程桌面
            pPLCConnInfoForm.ModifyRemoteInfoTextBox(computername,computerpasswd);
            System.Diagnostics.ProcessStartInfo Info = new System.Diagnostics.ProcessStartInfo();
            //设置外部程序名
            Info.FileName = "mstsc.exe";
            //设置外部程序的启动参数（命令行参数）
            remoteIp = "192.168.0.141";
            remotePort = "3389";

            Info.Arguments =System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
                + @"\Default.rdp /v:" + remoteIp + ":" + remotePort;

            System.Diagnostics.Process Proc;
            try
            {
                Proc = System.Diagnostics.Process.Start(Info);          
            }
            catch (System.ComponentModel.Win32Exception e)
            {
                Debug.WriteLine("系统找不到指定的程序文件。\r{0}", e);
                return;
            }

            //本程序结束时，需要做的清理工作
            Proc.EnableRaisingEvents = true;
            Proc.Exited += new EventHandler(proc_Exited);
            //开启一个后台线程抓去本程序的最终显示金额面到指定的框内，抓去后线程退出。
            Thread checkTheMstscThread = new Thread( new  ParameterizedThreadStart(CheckTheMstsc));
            checkTheMstscThread.IsBackground = true;
            CheckThreadIsGoing = true;
            checkTheMstscThread.Start(Proc);
        }
        /// <summary>
        /// 远程桌面退出清理工作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void proc_Exited(object sender, EventArgs e)
        {
            pPLCConnInfoForm.processIsRunning = false;
        }
        /// <summary>
        /// 抓远程桌面线程函数
        /// </summary>
        /// <param name="parm"></param>
        private void CheckTheMstsc(object parm)
        {
            Process Proc = (Process)parm;
            string name = "mstsc";
            Process[] pp = new Process[32];           
            while (!Proc.HasExited && CheckThreadIsGoing)
            {
                pp.Initialize();
                pp = Process.GetProcessesByName(name);
                for (int i = 0; i < pp.Length; i++)
                {
                    if (pp[i].ProcessName == name && pp[i].MainWindowTitle.ToString().Contains(remoteIp+":"+remotePort+" - 远程桌面连接"))
                    {                                                                           
                        pPLCConnInfoForm.processIsRunning = true;
                        //这里说明程序已找到并将要嵌入，激活关闭本程序的按钮。
                        if (this.InvokeRequired)
                            this.Invoke(new PLCConnInfoForm.RemoteDesktopButtonEnable(pPLCConnInfoForm.ModifyTheRemoteDesktopButtonEnable));
                        //调用嵌入程序，并退出线程。
                        if (this.InvokeRequired)
                            this.Invoke(new PLCConnInfoForm.RemoteDesktop(pPLCConnInfoForm.EmbedRemoteDesktop),pp[i]);    
                        CheckThreadIsGoing = false;                      
                    }
                }
                Thread.Sleep(1000);
            }         
        }
        /// <summary>
        /// 创建新的PLC全部参数框。
        /// </summary>
        public void CreatePLCAllParmsForm()
        {
            if (!PLCAllParmsFormIsExisted)
            {
                PLCAllParmsForm PLCAllParameterForm =
                    new PLCAllParmsForm(myStream, 
                                        mySocket, 
                                        myID, 
                                        currentPLCID, 
                                        currentPLCName, 
                                        this);
                pPLCAllParmsForm = PLCAllParameterForm;
                PLCAllParmsFormIsExisted = true;
                PLCAllParameterForm.Show();
            }
            else
                return;
        }
        /// <summary>
        /// 创建详细异常信息窗口并保留其对象
        /// </summary>
        /// <param name="startTime"></param>
        /// <param name="endTime"></param>
        public void CreatePLCAbnormalInfoForm(string startTime,string endTime)
        {
            if (!PLCAbnormalInfoFormIsExisted)
            {
                PLCAbnormalInfoForm PLCAbnormalInfomationForm =
                    new PLCAbnormalInfoForm(myStream,
                                            mySocket, 
                                            myID, 
                                            currentPLCID, 
                                            currentPLCName, 
                                            startTime,
                                            endTime,
                                            this);
                pPLCAbnormalInfoForm = PLCAbnormalInfomationForm;
                PLCAbnormalInfoFormIsExisted = true;
                PLCAbnormalInfomationForm.Show();
            }
            else
                return;
        }
        /// <summary>
        /// 显示列表中PLC异常信息
        /// </summary>
        /// <param name="important"></param>
        private void ModifyImportantMsgRichTextBox(string important)
        {
            this.importantMsgRichTextBox.Text = important;          
        }
        /// <summary>
        /// 显示PLC列表
        /// </summary>
        /// <param name="PLCs"></param>
        private void ModifyPLCListView(XmlDocument xDocument)
        {
            XmlTextReader r = new XmlTextReader(new StringReader(xDocument.OuterXml));
            PLCListDataSet = new DataSet();
            PLCListDataSet.ReadXml(r);
            DataTable data = PLCListDataSet.Tables["PLC"];
            if (data == null)
                return;
            BindingSource dataSource = new BindingSource(data, null);
            PLCListDataGridView.DataSource = dataSource;
            //PLCListDataGridView.DataSource = PLCsData;
            //PLCListDataGridView.Refresh();
        }
        /// <summary>
        /// 刷新按钮，需要清空上一次的排序 列号（Column = 0）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void refreshPLCListButton_Click(object sender, EventArgs e)
        {
            SendAndRecv.SendPLCListRequest(myStream, myID);
        }
        /// <summary>
        /// 关闭窗口
        /// </summary>
        private void CancelTheFormsRightNow()
        {
            theConnectionIsWrong = true;
            this.Close();
        }
        /// <summary>
        /// 返回按钮，确定后会关闭所有窗口，除了登录窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CancleButtonClick(object sender, System.ComponentModel.CancelEventArgs e)
        {
            //如果是连接断开出发的close事件
            if (theConnectionIsWrong)
            {
                this.Owner.Show();
                if (PLCAllParmsFormIsExisted)
                    pPLCAllParmsForm.Close();
                if (PLCConnInfoFormIsExisted)
                    pPLCConnInfoForm.Close();
                if (PLCAbnormalInfoFormIsExisted)
                    pPLCAbnormalInfoForm.Close();
                mySocket.Close();        
            }
            //否则为手动退出按钮
            else
            {
                DialogResult dialogResult = MessageBox.Show("你确定要退出么?", "退出提示", MessageBoxButtons.OKCancel);
                if (dialogResult == DialogResult.OK)//退出是有报文的
                {
                    SendAndRecv.SendLogoutRequest(myStream, myID);
                    e.Cancel = true;
                }
                else
                    e.Cancel = true;
            }
        }
        /// <summary>
        /// 点击了列会触发重新排序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ResortTheGridView(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridViewColumn clickedColumn = PLCListDataGridView.Columns[e.ColumnIndex];
            if (clickedColumn.SortMode != DataGridViewColumnSortMode.Automatic)
                this.SortRows(clickedColumn, true);
            else
                this.SortRows(clickedColumn, true);

        }
        /// <summary>
        /// 排序方法
        /// </summary>
        /// <param name="sortColumn"></param>
        /// <param name="orderToggle"></param>
        private void SortRows(DataGridViewColumn sortColumn, bool orderToggle)
        {
            if (sortColumn == null)
                return;

            //清除前面的排序
            if (sortColumn.SortMode == DataGridViewColumnSortMode.Programmatic &&
                PLCListDataGridView.SortedColumn != null &&
                !PLCListDataGridView.SortedColumn.Equals(sortColumn))
            {
                PLCListDataGridView.SortedColumn.HeaderCell.SortGlyphDirection =
                    SortOrder.None;
            }

            //设定排序的方向（升序、降序）
            ListSortDirection sortDirection;
            if (orderToggle)
            {
                sortDirection =
                    PLCListDataGridView.SortOrder == SortOrder.Descending ?
                    ListSortDirection.Ascending : ListSortDirection.Descending;
            }
            else
            {
                sortDirection =
                    PLCListDataGridView.SortOrder == SortOrder.Descending ?
                    ListSortDirection.Descending : ListSortDirection.Ascending;
            }
            SortOrder sortOrder =
                sortDirection == ListSortDirection.Ascending ?
                SortOrder.Ascending : SortOrder.Descending;

            //进行排序
            PLCListDataGridView.Sort(sortColumn, sortDirection);

            if (sortColumn.SortMode == DataGridViewColumnSortMode.Programmatic)
            {
                //变更排序图标
                sortColumn.HeaderCell.SortGlyphDirection = sortOrder;
            }
        }
        /// <summary>
        /// 获得选中的PLCID和PLCName，创建新的PLC联系信息窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SelectPLCID_Click(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == 0)
            {
                if (e.RowIndex != -1)// && e.RowIndex ==int.Parse( PLCListDataGridView.CurrentRow.ToString()))               
                {
                    currentPLCID = PLCListDataGridView.CurrentCell.Value.ToString();
                    currentPLCName = PLCListDataGridView.CurrentRow.Cells[1].Value.ToString();
                    PLCConnInfoForm PLCConnectionInfoForm = new PLCConnInfoForm(myStream, mySocket, myID, currentPLCID, currentPLCName, this);
                    PLCConnInfoFormIsExisted = true;                                     
                    pPLCConnInfoForm = PLCConnectionInfoForm;
                    PLCConnectionInfoForm.Owner = this;
                    this.Hide();
                    PLCConnectionInfoForm.Show();
                }
            }
            else
                return;
        }
        /// <summary>
        /// PLCList刷新之后修改表头
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PLCListDataGridView_DataBindingComplete(object sender,
                                            DataGridViewBindingCompleteEventArgs e)
        {
            try
            {
                PLCListDataGridView.Columns["PLCID"].HeaderText = "PLC-ID";
                PLCListDataGridView.Columns["PLCName"].HeaderText = "PLC名称";
                PLCListDataGridView.Columns["status"].HeaderText = "在线/离线";
                PLCListDataGridView.Columns["company"].HeaderText = "公司";
                PLCListDataGridView.Columns["project"].HeaderText = "项目";
                PLCListDataGridView.Columns["abnormal"].HeaderText = "正常/异常";
                PLCListDataGridView.Columns["msg"].HeaderText = "异常消息";//隐藏某列：

                String filterStatus = DataGridViewAutoFilterColumnHeaderCell
                .GetFilterStatus(PLCListDataGridView);
                if (String.IsNullOrEmpty(filterStatus))
                {
                    showAllLabel.Visible = false;
                    filterStatusLabel.Visible = false;
                }
                else
                {
                    showAllLabel.Visible = true;
                    filterStatusLabel.Visible = true;
                    filterStatusLabel.Text = filterStatus;
                }
            }
            catch(Exception ex)
            {
                Trace.WriteLine(ex.Message);
                return;
            }

        }

        private void PLCListDataGridView_BindingContextChanged(object sender, EventArgs e)
        {
            if (PLCListDataGridView.DataSource == null)
            {
                return;
            }
            // Add the AutoFilter header cell to each column.
            foreach (DataGridViewColumn col in PLCListDataGridView.Columns)
            {
                col.HeaderCell = new DataGridViewAutoFilterColumnHeaderCell(col.HeaderCell);
            }

            // Resize the columns to fit their contents.
            PLCListDataGridView.AutoResizeColumns();
        }

        private void showAllLabel_Click(object sender, EventArgs e)
        {
            DataGridViewAutoFilterColumnHeaderCell.RemoveFilter(PLCListDataGridView);
        }

        private void modifyPersonalInfoButton_Click(object sender, EventArgs e)
        {
            if (!modifyPersonalInfoFormIsExisted)
            {
                ModifyPersonalInfoForm ModifyPersonalInformationForm = new ModifyPersonalInfoForm(myStream,myID,this);
                modifyPersonalInfoFormIsExisted = true;
                pModifyPersonalInfoForm = ModifyPersonalInformationForm;
                ModifyPersonalInformationForm.Show();
            }
            else if(pModifyPersonalInfoForm!=null)
                pModifyPersonalInfoForm.Show();
        }
    }
}
